package user

import (
	"github.com/infraboard/mcube/pb/resource"
	"golang.org/x/crypto/bcrypt"
)

func NewUser(in *CreateUserRequest) *User {
	// 先Hash再保持
	in.MakePasswordHash()
	return &User{
		Meta: resource.NewMeta(),
		Spec: in,
	}
}

func (i *User) CheckPassword(password string) error {
	return bcrypt.CompareHashAndPassword([]byte(i.Spec.Password), []byte(password))
}

func NewCreateUserRequest() *CreateUserRequest {
	return &CreateUserRequest{
		RoleIds: []string{},
	}
}

func (r *CreateUserRequest) MakePasswordHash() {
	bytes, err := bcrypt.GenerateFromPassword([]byte(r.Password), 10)
	if err != nil {
		panic(err)
	}
	r.Password = string(bytes)
}
